package com.liws.hellojuc.reentrantLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ：liweisheng
 * @date ：2022/1/31 7:08
 * @description：响应中断与限时等待
 */
public class ReentrantLockTest03 {
    static final Lock lock1=new ReentrantLock();
    static final Lock lock2=new ReentrantLock();

    public static void main(String[] args) {
       // testInterruptThread();
        testTimeLimitThread();
    }

    //响应中断
    static void testInterruptThread(){
        // 中断线程A,但是不影响线程B获取锁
        Thread firstThread = new Thread(new InterruptThreadDemo(lock1, lock2),"线程A");
        Thread secondThread = new Thread(new InterruptThreadDemo(lock2, lock1),"线程B");
        firstThread.start();
        secondThread.start();
        firstThread.interrupt();
    }

    //限时等等
    static void testTimeLimitThread(){
        Thread firstThread = new Thread(new TimeLimitThreadDemo(lock1, lock2),"线程A");
        Thread secondThread = new Thread(new TimeLimitThreadDemo(lock2, lock1),"线程B");
        firstThread.start();
        secondThread.start();
    }

    static class InterruptThreadDemo implements Runnable{

        Lock firstLock;
        Lock secondLock;
        public InterruptThreadDemo(Lock firstLock,Lock secondLock){
            this.firstLock=firstLock;
            this.secondLock=secondLock;
        }
        @Override
        public void run() {

            try {
                firstLock.lockInterruptibly();
                TimeUnit.MILLISECONDS.sleep(50);
                secondLock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                firstLock.unlock();
                secondLock.unlock();
                System.out.println(Thread.currentThread().getName()+"获取资源，正常结束！");
            }

        }
    }

    static class TimeLimitThreadDemo implements Runnable{
        Lock firstLock;
        Lock secondLock;
        public TimeLimitThreadDemo(Lock firstLock,Lock secondLock){
            this.firstLock=firstLock;
            this.secondLock=secondLock;
        }
        @Override
        public void run() {
            try {
                if (!firstLock.tryLock()){
                    TimeUnit.MILLISECONDS.sleep(10);
                }

                if (!secondLock.tryLock()){

                    TimeUnit.MILLISECONDS.sleep(10);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                firstLock.unlock();
                secondLock.unlock();
                System.out.println(Thread.currentThread().getName()+"正常结束！");
            }


        }
    }
}
